var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 允许所有来源跨域
app.use(cors());



// 在路由之前封装
app.use((req, res, next) => {
  // 默认值为1，表示失败的情况
  res.cc = function (err, status = 1, code = 400) {
    // 如果 err 是字符串，直接用
    if (typeof err === 'string') {
      res.status(code).send({ status, code, message: err });
    } else if (err instanceof Error) {
      res.status(code).send({ status, code, message: err.message });
    } else if (typeof err === 'object' && err.message) {
      res.status(code).send({ status, code: err.code || code, message: err.message });
    } else {
      res.status(code).send({ status, code, message: '未知错误' });
    }
  }
  next()
})


// 导入并注册用户路由
const userRouter = require('./routes/users');
app.get('/', (req, res) => {
  res.send('API服务已启动');
});
app.use('/users', userRouter);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});


// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


app.listen(3010, '0.0.0.0', function () {
  console.log('api server is running at 3010');
})
